package demo;

import helloword.MyService;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.async.TAsyncClientManager;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocolFactory;
import org.apache.thrift.transport.TNonblockingSocket;
import org.apache.thrift.transport.TNonblockingTransport;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class TestAsyncClient {

    public static void main(String[] args) throws IOException, TException {

        CountDownLatch countDownLatch = new CountDownLatch(2);

        //配置SocketChannel
        TNonblockingTransport tTransport = new TNonblockingSocket("localhost", 8080);

        TProtocolFactory tProtocolFactory = new TBinaryProtocol.Factory();

        //启动一个线程 这个线程一直在while循环中跑 当异步的client调用方法的时候 会生成一个methodCall对象添加到这个管理器的Queue中
        //然后这个已经启动的线程里的run方法拿到这个任务 就向远程主机进行connect和发送序列化后的数据
        TAsyncClientManager tAsyncClientManager = new TAsyncClientManager();
        MyService.AsyncClient asyncClient = new MyService.AsyncClient(tProtocolFactory, tAsyncClientManager, tTransport);

        //生成一个Future  在onComplete方法onCompete方法执行后 设置Future.done


        asyncClient.say("hello world", 23, new AsyncMethodCallback<MyService.AsyncClient.say_call>() {

            @Override
            public void onComplete(MyService.AsyncClient.say_call response) {
                try {
                    System.out.println(response.getResult());
                    countDownLatch.countDown();
                } catch (TException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Exception exception) {

            }
        });

        MyService.AsyncClient asyncClient2 = new MyService.AsyncClient(tProtocolFactory, tAsyncClientManager, tTransport);

        asyncClient2.say("hello world", 23, new AsyncMethodCallback<MyService.AsyncClient.say_call>() {

            @Override
            public void onComplete(MyService.AsyncClient.say_call response) {
                try {
                    System.out.println(response.getResult());
                    countDownLatch.countDown();
                } catch (TException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Exception exception) {

            }
        });

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
